#include <winsock2.h>
#include <iostream>
#include <WS2tcpip.h>

#pragma comment(lib, "WS2_32.lib")
const unsigned int PORT = 11024;
const int kBufferSize = 1024;

int main() {

	WSADATA wsData;
	if (WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
		std::cout << "start up failed\n" << std::endl;
		return 0;
	}
	// connect the socket;

	SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	SOCKADDR_IN addIn;
	addIn.sin_family = AF_INET;
	addIn.sin_port = htons(PORT);
	//addIn.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
	struct in_addr temp_addr;
	inet_pton(AF_INET, "127.0.0.1", (void *)&temp_addr);
	addIn.sin_addr.S_un.S_addr = temp_addr.s_addr;
	
	char cSendBuffer[kBufferSize] = "Client sends a Message to the Server, please confirm?";
	int bRecvLen = sizeof(addIn);
	int bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
	while (bSendRet != SOCKET_ERROR) {
		char cRecvBuffer[kBufferSize] = "#";
		int bRecv = recvfrom(s, cRecvBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, &bRecvLen);
		if (bRecv != SOCKET_ERROR) {
			std::cout << "Client recvie the infromation from the server is: " << cRecvBuffer << std::endl;
			ZeroMemory(cSendBuffer, kBufferSize);
			std::cout << "please input the information the sends to the server: ";
			std::cin >> cSendBuffer;
			bSendRet = sendto(s, cSendBuffer, kBufferSize, 0, (LPSOCKADDR)&addIn, sizeof(addIn));
		}
		else {
			break;
		}
	}

	if (WSACleanup() != 0) {
		std::cout << "clean up failed\n";
		return -1;
	}
	closesocket(s);
	return 0;
}